package com.xinzhitong.www.utils;

/**
 * 密文工具
 *
 * @author 徐鑫
 */
public class SecretUtil {

    /**
     * 为用户名简单加密
     *
     * @param username 用户名 如：13188888888
     * @param salt     盐（即加密算子，需6位）如：824659
     * @return 加密后的用户名
     */
    public static String hide(String username, String salt) {
        char[] usernameChars = username.toCharArray();
        char[] saltChars = salt.toCharArray();
        for (int i = 0; i < usernameChars.length; i++)
            usernameChars[i] = (char) ((usernameChars[i] - '0' + saltChars[i % saltChars.length] - '0') % 10 + '0');
        return String.valueOf(usernameChars);
    }

    /**
     * 为密文解密
     *
     * @param secretCode 密文
     * @param salt       原盐
     * @return 原文
     */
    public static String expose(String secretCode, String salt) {
        char[] secretCodeChars = secretCode.toCharArray();
        char[] saltChars = salt.toCharArray();
        int[] secretCodeNumbers = new int[secretCodeChars.length];
        int[] saltNumbers = new int[saltChars.length];
        for (int i = 0; i < saltChars.length; i++)
            saltNumbers[i] = saltChars[i] - '0';
        for (int i = 0; i < secretCodeNumbers.length; i++) {
            secretCodeNumbers[i] = secretCodeChars[i] - '0';
            secretCodeNumbers[i] -= saltNumbers[i % saltChars.length];
            if (secretCodeNumbers[i] < 0)
                secretCodeNumbers[i] += 10;
            secretCodeChars[i] = (char) (secretCodeNumbers[i] + 48);
        }
        return String.valueOf(secretCodeChars);
    }

}
